/**
 * 自动刷新token，触发条件为用户持续有操作
 * @param route
 * @param formData
 * @param type
 * @param dataType
 * @returns {Promise<unknown>}
 */
function requestHost(route, formData, type = 'GET', dataType = 'json') {
    let JWTTOKEN_EXPIRE_AT = parseInt(localStorage.getItem('JWTTOKEN_EXPIRE_AT'))
    let timeOver = JWTTOKEN_EXPIRE_AT - (new Date()).getTime().valueOf();//这里必须实时获取时间
    if ($.inArray(window.location.pathname, NEED_NOT_TOKEN) === -1 && timeOver > 0 && timeOver < REFRESH_TOKEN_AT) {
        return request('token/refresh_token', {}).then(function (res) {
            saveToken(res.data.token)
            return request(route, formData, type, dataType)
        })
    } else {
        return request(route, formData, type, dataType)
    }
}


function request(route, formData, type = 'GET', dataType = 'json') {
    return new Promise(function (resolve, reject) {
        $.ajax({
            headers: {
                "JWTTOKEN": localStorage.getItem('JWTTOKEN')
            },
            url: SERVICE_HOST + '/' + route,
            data: formData,
            type: type,
            dataType: dataType,
            success: function (res) {
                if (parseInt(res.errCode) === 200) {
                    return resolve(res)
                } else if (parseInt(res.errCode) === 401) {
                    clearToken()
                    redirectLogin()
                }

                $.growl.error({
                    title: "错误提示",
                    message: res.msg
                });
            },
            fail: function (error) {
                reject(error)
            }
        })
    })
}

function redirectLogin() {
    if (window.location.pathname !== LOGIN_PATH && window.location.pathname !== REGISTER_PATH) {
        window.location.href = LOGIN_PATH;
    }
}

/**
 * 如果已登录，则不允许跳转到登录和注册页
 */
function redirectIndex() {
    if ($.inArray(window.location.pathname, [LOGIN_PATH, REGISTER_PATH]) !== -1 && parseInt(localStorage.getItem('JWTTOKEN_EXPIRE_AT')) > (new Date).getTime().valueOf()) {

        window.location.href = INDEX_PATH;
    }
}

function saveToken(token) {
    localStorage.setItem('JWTTOKEN', token)
    localStorage.setItem('JWTTOKEN_EXPIRE_AT', (new Date).getTime().valueOf() + TOKEN_EXPIRE)//这里时间千万要大于一小时，不然会进入死循环
}

function clearToken() {
    localStorage.clear()
}

redirectIndex()